package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    DishFlavorService dishFlavorService;

    /**
     * 自定义 保存菜品信息的service层方法
     *
     * @param dishDto
     */
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {

        //先保存dish
        this.save(dishDto);


        //保存dish后 通过MP获取菜品id
        Long dishDtoId = dishDto.getId();

        //将id存入flavors中
        List<DishFlavor> flavors = dishDto.getFlavors();


        flavors = flavors.stream().map(new Function<DishFlavor, DishFlavor>() {
            @Override
            public DishFlavor apply(DishFlavor dishFlavor) {
                dishFlavor.setDishId(dishDtoId);
                return dishFlavor;
            }
        }).collect(Collectors.toList());

        //保存flavors信息
        for (DishFlavor flavor : flavors) {
            dishFlavorService.save(flavor);
        }

    }

    /**
     * 自定义 更新菜品信息的方法
     * @param dishDto
     */
    @Override
    @Transactional
    public void upDataWithFlavors(DishDto dishDto) {

        LambdaQueryWrapper<Dish> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Dish::getId,dishDto.getId());

        this.update(dishDto,lambdaQueryWrapper);


        //删除口味表中的信息

        LambdaQueryWrapper<DishFlavor> flavorLambdaQueryWrapper=new LambdaQueryWrapper<>();
        flavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDto.getId());

        dishFlavorService.remove(flavorLambdaQueryWrapper);

        //将dishDto中的口味信息重新插入
        List<DishFlavor> flavors = dishDto.getFlavors();

        //在flavor中设置dishId
        flavors=flavors.stream().map(flavor->{

            flavor.setDishId(dishDto.getId());
            return flavor;

        }).collect(Collectors.toList());



        for (DishFlavor flavor : flavors) {
            dishFlavorService.save(flavor);
        }

    }
}
